package com.store.practice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;

import com.store.practice.common.utils.UploadPicUtil;
import com.store.practice.dto.StaffUpdateParam;
import com.store.practice.mapper.*;
import com.store.practice.model.*;
import com.store.practice.service.BgStoreStaffService;

import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BgStoreStaffServiceImpl implements BgStoreStaffService {
    private static final Logger logger = LoggerFactory.getLogger(BgStoreStaffServiceImpl.class);
    @Autowired
    private UploadPicUtil uploadPicUtil;
    @Autowired
    private BgStoreStaffMapper staffMapper;
    @Autowired
    private BgStorestaffSkilltagRelationMapper storestaffSkilltagRelationMapper;
    @Autowired
    private BgSkillTagMapper tagMapper;
    @Autowired
    private AppAccountMapper accountMapper;
    @Autowired
    private BgAppointmentOrderMapper orderMapper;
    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;
    @Value("${minio.defaultPicture-url}")
    private String DEFAULT_PIC;

    @Override
    public Map upload(MultipartFile file){
        try{
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            boolean isExists = minioClient.bucketExists(BUCKET_NAME);
            if (isExists){
                logger.info("存储桶已经存在");
            }else {
                minioClient.makeBucket(BUCKET_NAME);
                minioClient.setBucketPolicy(BUCKET_NAME,"*.*", PolicyType.READ_ONLY);
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            String originalFilename = file.getOriginalFilename();
            if (uploadPicUtil.judgeSuffix(originalFilename)){
                //设置存储对象名称
                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                String objectName = format.format(new Date()) + "/" + uuid + originalFilename;
                minioClient.putObject(BUCKET_NAME,objectName,file.getInputStream(),file.getContentType());
                logger.info("文件上传成功");
                HashMap<String, String> result = new HashMap<>();
                result.put("fileName",uuid+originalFilename);
                result.put("url",ENDPOINT+"/"+BUCKET_NAME+"/"+objectName);
                return result;
            }
        }catch (Exception e){
            logger.error("文件上传失败,{}",e.getMessage());
        }
        return null;
    }

    @Override
    public List<Map> list() {
        List<BgStoreStaff> list = staffMapper.selectByExample(null);
        ArrayList<Map> result = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (list!=null){
            for (BgStoreStaff staff:list){
                List<Integer> ids = storestaffSkilltagRelationMapper.getTagIdsByStaffId(staff.getId());
                ArrayList<String> skillNames = new ArrayList<>();
                if (ids!=null){
                    for (Integer skillId:ids){
                        String tag = tagMapper.selectByPrimaryKey(skillId).getTag();
                        skillNames.add(tag);
                    }
                }
                map = BeanUtil.beanToMap(staff);
                map.put("skillNames",skillNames);
                result.add(map);
            }
        }
        return result;
    }

    @Override
    public Map getStaffById(Integer id) {
        Map<String, Object> result = new HashMap<>();
        BgStoreStaff staff = staffMapper.selectByPrimaryKey(id);
        List<Integer> ids = storestaffSkilltagRelationMapper.getTagIdsByStaffId(staff.getId());
        ArrayList<String> skillNames = new ArrayList<>();
        if (ids!=null){
            for (Integer skillId:ids){
                String tag = tagMapper.selectByPrimaryKey(skillId).getTag();
                skillNames.add(tag);
            }
        }
        result = BeanUtil.beanToMap(staff);

        result.put("skillNames",skillNames);
        result.put("gender",staff.getGender().equals(0)?"男":"女");
        result.put("birthday", DateUtil.format(staff.getBirthday(),"yyyy-MM-dd"));
        return result;
    }

    @Override
    public int insert(Integer accountId,List<Integer> tagIds,BgStoreStaff staff) {
        staff.setAccountId(accountId);
        staff.setPicture(ENDPOINT+"/"+BUCKET_NAME+"/"+DEFAULT_PIC);
        Long phone = accountMapper.selectByPrimaryKey(accountId).getPhone();
        if (phone==null){
            return -1;
        }
        staff.setNickname(phone.toString());
        int i = staffMapper.insert(staff);
        Integer staffId = staff.getId();
        for (Integer id:tagIds){
            BgStorestaffSkilltagRelation relation = new BgStorestaffSkilltagRelation();
            relation.setSkillId(id);
            relation.setStaffId(staffId);
            storestaffSkilltagRelationMapper.insert(relation);
        }
        return i;
    }

    @Override
    public Map getApp(Integer accountId) {
        HashMap<String, Object> result = new HashMap<>();
        BgStoreStaffExample example = new BgStoreStaffExample();
        example.createCriteria().andAccountIdEqualTo(accountId);
        List<BgStoreStaff> bgStoreStaffs = staffMapper.selectByExample(example);
        if (bgStoreStaffs==null||bgStoreStaffs.size()==0){
            return null;
        }
        BgStoreStaff staff = bgStoreStaffs.get(0);
        if (staff.getStatus().equals(0)){
            result.put("errorMg","审核中");
            return result;
        }
        result.put("header",staff.getPicture());
        result.put("realname",staff.getName());
        result.put("staffId",staff.getId());
        result.put("storeId",staff.getStoreId());
        return result;
    }

    @Override
    public Map getStaff(Integer id) {
        Map<String, Object> result;
        BgStoreStaff staff = staffMapper.selectByPrimaryKey(id);
        List<Integer> ids = storestaffSkilltagRelationMapper.getTagIdsByStaffId(staff.getId());
        ArrayList<String> skillNames = new ArrayList<>();
        if (ids!=null){
            for (Integer skillId:ids){
                String tag = tagMapper.selectByPrimaryKey(skillId).getTag();
                skillNames.add(tag);
            }
        }
        result = BeanUtil.beanToMap(staff);
        result.put("picture",staff.getPicture());
        result.put("skillNames",skillNames);
        result.put("nickname",staff.getNickname());
        result.put("position",staff.getPosition());
        return result;
    }

    @Override
    public int updateApp(Integer staffId,String fileUrl, StaffUpdateParam param) {
        BgStoreStaff staff = new BgStoreStaff();
        staff.setNickname(param.getNickname());
        BgStorestaffSkilltagRelationExample relationExample = new BgStorestaffSkilltagRelationExample();
        relationExample.createCriteria().andStaffIdEqualTo(staffId);
        storestaffSkilltagRelationMapper.deleteByExample(relationExample);
        staff.setPicture(fileUrl);
        staff.setIntroduction(param.getIntroduction());
        staff.setPosition(param.getPosition());
        BgStoreStaffExample example = new BgStoreStaffExample();
        example.createCriteria().andIdEqualTo(staffId);
        int i = staffMapper.updateByExampleSelective(staff, example);
        List<Integer> tagIds = param.getTagIds();
        for (Integer id:tagIds){
            BgStorestaffSkilltagRelation relation = new BgStorestaffSkilltagRelation();
            relation.setSkillId(id);
            relation.setStaffId(staffId);
            storestaffSkilltagRelationMapper.insert(relation);
        }
        return i;
    }

    @Override
    public List<Map> getOrder(Integer staffId) {
        String bName = staffMapper.selectByPrimaryKey(staffId).getName();
        BgAppointmentOrderExample example = new BgAppointmentOrderExample();
        example.createCriteria().andBeauticianEqualTo(bName);
        example.setOrderByClause("end_time desc");
        List<BgAppointmentOrder> orders = orderMapper.selectByExample(example);
        List<Map> result = new ArrayList<>();
        if (orders!=null&&orders.size()>0){
            Map<String, Object> map = new HashMap<>();
            for (BgAppointmentOrder order:orders){
                map = BeanUtil.beanToMap(order);
                map.put("serviceDate",DateUtil.format(order.getServiceDate(),"yyyy-MM-dd"));
                map.put("startTime",DateUtil.format(order.getStartTime(),"HH:mm:SS"));
                map.put("endTime",DateUtil.format(order.getEndTime(),"HH:mm:SS"));
                if (order.getStatus()==0){
                    map.put("status","未完成");
                }else if (order.getStatus()==1){
                    map.put("status","预约中");
                }else if (order.getStatus()==2){
                    map.put("status","已完成");
                }
                result.add(map);
            }
            return result;
        }
        return null;
    }

    @Override
    public int updateStatus(Integer orderId,Integer param) {
        BgAppointmentOrder order = orderMapper.selectByPrimaryKey(orderId);
        if (param==0){
            order.setStatus(0);
        }
        if (param==1){
            order.setStatus(2);
        }
        return orderMapper.updateByPrimaryKey(order);
    }

}
